package com.qdu.spring.blog.aop;

import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionInterceptor;

/**
 * 配置全局事务支持
 *
 *
 *
 */
@Aspect
public class TransactionAop {
    private static final String AOP_POINTCUT_EXPRESSION = "execution (* com.***.service.*.*(..))";

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Bean
    public TransactionInterceptor txAdvice()
    {
        DefaultTransactionAttribute txattrRequired = new DefaultTransactionAttribute();
        txattrRequired.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        DefaultTransactionAttribute txattrRequiredReadonly = new DefaultTransactionAttribute();
        txattrRequiredReadonly.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        txattrRequiredReadonly.setReadOnly(true);

        NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
        source.addTransactionalMethod("add*", txattrRequired);
        source.addTransactionalMethod("insert*", txattrRequired);
        source.addTransactionalMethod("save*", txattrRequired);
        source.addTransactionalMethod("delete*", txattrRequired);
        source.addTransactionalMethod("update*", txattrRequired);
        source.addTransactionalMethod("exec*", txattrRequired);
        source.addTransactionalMethod("set*", txattrRequired);

        source.addTransactionalMethod("get*", txattrRequiredReadonly);
        source.addTransactionalMethod("select*", txattrRequiredReadonly);
        source.addTransactionalMethod("query*", txattrRequiredReadonly);
        source.addTransactionalMethod("find*", txattrRequiredReadonly);
        source.addTransactionalMethod("list*", txattrRequiredReadonly);
        source.addTransactionalMethod("count*", txattrRequiredReadonly);
        source.addTransactionalMethod("is*", txattrRequiredReadonly);
        return new TransactionInterceptor(transactionManager, source);
    }

    @Bean
    public Advisor txAdviceAdvisor()
    {
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
        return new DefaultPointcutAdvisor(pointcut, txAdvice());
    }
}
